package com.pagoda.nerp.trade.app.account.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.common.httputil.HttpClientConnectionManager;
import com.pagoda.nerp.trade.common.objectutil.PropertyConfigurer;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class VerifyCodeUtil {
	
	private static final Logger logger = Logger.getLogger(VerifyCodeUtil.class.getName());

	private static boolean debug = false;

	static {
		debug = Boolean.parseBoolean(PropertyConfigurer.parseStr("sys.sms.debug"));
	}

	/**
	 * http接口调用
	 * @param msg
	 * @param url
	 * @return
	 */
	public static int sendHttpReq(String msg,String url){
		int errorCode=0;
		if(debug){
			return errorCode;
		}
		HttpPost post=null;
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			httpClient = (DefaultHttpClient) HttpClientConnectionManager .getSSLInstance(httpClient);
			post = HttpClientConnectionManager.getPostMethod(url);
			post.setEntity(new StringEntity(msg, "utf-8"));
			HttpResponse response = httpClient.execute(post);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			logger.info("back value of send http request："+jsonStr);
			JSONObject jsonObj = JSON.parseObject(jsonStr);
			errorCode=jsonObj.getInteger("errorCode");
		} catch (Exception e) {
			logger.error("send http request failed：",e);
			return ErrorCodeMappingEnums.ERROR_HTTP_REQUEST_FAIL.getErrorCode();
		}finally{
			if(post!=null){
				post.releaseConnection();
				post = null;
			}
		}
		return errorCode;
	}
	
	public static String createRandomVcode() {
		// 验证码
		String vcode = "";
		for (int i = 0; i < 4; i++) {
			vcode = vcode + (int) (Math.random() * 9);
		}
		return vcode;
	}
}
